﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;


namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// DDM定时更新库存
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UpdateStockInventoryController : ControllerBase
    {
        private readonly ILogger<WMSInterfaceRequestDto> _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_qh;


        public UpdateStockInventoryController(ILogger<WMSInterfaceRequestDto> logger,IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration)
        {
            _logger = logger;
            _WMSTokenCheckService = wmsTokenCheckService;
             con= _configuration.GetConnectionString("DDM_DbConnection_Test2");

        }

        /// <summary>
        /// DDM定时更新库存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PosUpdateStockInventory([FromBody] WMSInterfaceRequestDto strparm)
        {
            string  strMsg = "";
            object log = "";
            log = strparm;
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            WMSInterfaceRequestDto result = new WMSInterfaceRequestDto();
            WMSInterfaceResponseDto re = new WMSInterfaceResponseDto();
            try
            {
             

                strSql = new StringBuilder();
                strSql.Append("select * from wms_gxitem_middle where in_status is null");
                DataTable dt_check= DB.Query(strSql.ToString(), con);
                if (dt_check.Rows.Count>0)
                {
                    strSql = new StringBuilder();
                    strSql.Append("delete from gx_update_inventory");
                    strSqlList.Add(strSql.ToString());
                    strSql = new StringBuilder();
                    strSql.Append("insert into gx_update_inventory  select * from wms_gxitem_middle where in_status is null");
                    strSqlList.Add(strSql.ToString());
                    if (strSqlList.Count > 0)
                    {
                        bool A = DB.ExecuteNoQueryTran(strSqlList, con);

                    }
                    strSql = new StringBuilder();
                    strSql.Append(@"select * from gx_update_inventory");
                    DataTable dt_barcodecheck = DB.Query(strSql.ToString(), con);
                    if (dt_barcodecheck.Rows.Count > 0)
                    {
                        strSql = new StringBuilder();
                        strSql.Append(@"select max(id) id,max(document_id) doid from stock_inventory");
                        DataTable dt_maxid = DB.Query(strSql.ToString(), con);
                        string maxid = dt_maxid.Rows[0]["id"].ToString().Trim();
                        string doid = dt_maxid.Rows[0]["doid"].ToString().Trim();
                        int i = 1;
                        strSqlList = new List<string>();
                        strSql = new StringBuilder();
                        strSql.Append(@"select supplier_code,supplier_name,warehouse_code,warehouse_name,sum(material_amount) material_amount  from 
(select supplier_code,supplier_name,in_warehouse_code warehouse_code,in_warehouse_name warehouse_name,sum(material_amount)material_amount  from 
gx_update_inventory where in_status is null and in_warehouse_code is not null and in_warehouse_code='JWFC01'  group by supplier_code,supplier_name,in_warehouse_code,in_warehouse_name
union all
select supplier_code,supplier_name,out_warehouse_code warehouse_code,out_warehouse_name warehouse_name,-sum(material_amount)material_amount  
from  gx_update_inventory  where out_warehouse_code is not null  and in_status is null and out_warehouse_code='JWFC01'  group by supplier_code,supplier_name,out_warehouse_code,out_warehouse_name) s 
group by supplier_code,supplier_name,warehouse_code,warehouse_name");
                        DataTable dt_ls = DB.Query(strSql.ToString(), con);
                        foreach (DataRow row in dt_ls.Rows)
                        {
                            string material_amount = row["material_amount"].ToString();
                            string supplier_name = row["supplier_name"].ToString();
                            string warehouse_name = row["warehouse_name"].ToString();

                            strSql = new StringBuilder();
                            strSql.Append(@"select * from stock_inventory where supplier_code='" + row["supplier_code"].ToString().Trim() + "' and  warehouse_code='" + row["warehouse_code"].ToString().Trim() + "'  LIMIT 1");
                            DataTable dt_checkkc = DB.Query(strSql.ToString(), con);
                            if (dt_checkkc.Rows.Count > 0)
                            {
                                strSql = new StringBuilder();
                                strSql.Append(@"update stock_inventory set material_amount=(material_amount+" + material_amount + ") where supplier_code='" + row["supplier_code"].ToString().Trim()+ "' and  warehouse_code='" + row["warehouse_code"].ToString().Trim() + "'");
                                strSqlList.Add(strSql.ToString());
                            }
                            else
                            {
                                strSql = new StringBuilder();
                                strSql.Append("INSERT INTO stock_inventory  (id,document_id,status,tenant_id,form_id,owner,created_by,creation_date,last_updated_by,last_update_date,object_version_number,warehouse_code," +
                                    "warehouse_name,supplier_code,supplier_name, material_amount,ddate) VALUES (" + maxid + "+" + i + " ," + doid + "+" + i + " ,'COMPLETED',  '329584101155667969', '6329261346c3212a36b55cc1',  '100337312575492456448', '100337312575492456448', SYSDATE()," +
                                    "'100337312575492456448',SYSDATE(), 1, '" + row["warehouse_code"].ToString().Trim() + "', '" + warehouse_name + "', '" + row["supplier_code"].ToString().Trim() + "', '" + supplier_name + "', " + material_amount + ", SYSDATE())");
                                strSqlList.Add(strSql.ToString());
                                i++;
                            }

                        }
                        if (strSqlList.Count > 0)
                        {

                            bool A = DB.ExecuteNoQueryTran(strSqlList, con);
                            if (A)
                            {
                                strSqlList = new List<string>();
                                strSql = new StringBuilder();
                                strSql.Append(@"update wms_gxitem_middle set in_status='" + DateTime.UtcNow.ToString("yyMMddHHmmss") + "'  where id in (select id from gx_update_inventory)");
                                strSqlList.Add(strSql.ToString());
                                if (strSqlList.Count > 0)
                                {
                                    A = DB.ExecuteNoQueryTran(strSqlList, con);
                                }
                            }

                        }

                    }
                }

             

            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

         


            if (strMsg=="")
            {
                re.status = "成功";
                re.code = "1";
                re.message = "";
            }
            else
            {
                re.status = "失败";
                re.code = "0";
                re.message = strMsg;
            }


            return new JsonResult(re);
        }





    }
}
